package books.storage.eao;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import books.storage.entity.AuthorEntity;


@LocalBean
@Stateless
public class AuthorManagerEao implements IAuthorManagerEao {

    @PersistenceContext
    EntityManager em;
    
    public AuthorManagerEao() { }
    
    public AuthorManagerEao(EntityManager em) { this.em = em; } // for unit test
	
	public AuthorEntity authorByName(String authorName) {
		AuthorEntity result;
        Query q = em.createQuery("select a from Author a where a.name = :name");
        q.setParameter("name", authorName);
        result = (AuthorEntity) q.getSingleResult();
        return result;
	}

	@SuppressWarnings("unchecked")
	public List<AuthorEntity> authorByBook(String bookTitle) {
		List<AuthorEntity> result;
        Query q = em.createQuery("SELECT a FROM Author a WHERE a.id IN (SELECT b.author.id FROM Book b WHERE b.title like :title)");
        q.setParameter("tile", bookTitle + "%");
        result = (List<AuthorEntity>) q.getResultList();
        return result;
	}

}